package com.itheima.recursion_multi;

import java.util.Arrays;

/**
 * @FileName E01Fibonacci
 * @Description
 * @Author Sword
 * @date 2025-03-13
 **/
public class E01Fibonacci {


    /**
     * 使用Memoization(记忆法，也称备忘录)改进
     *
     * @param n
     * @return
    public static int fibonacci(int n) {
        if (n == 0) {
            return 0;
        }
        int[] cache = new int[n + 1];
        Arrays.fill(cache, -1);

        cache[0] = 0;
        cache[1] = 1;

        return f(n, cache);
    }

    private static int f(int n, int[] cache) {
        if (cache[n] != -1) {
            return cache[n];
        }

        int x = f(n - 1, cache);
        int y = f(n - 2, cache);
        cache[n] = x + y;   //存入数组
        return cache[n];
    }*/

    /**
     * 使用Memoization(记忆法，也称备忘录)改进
     *
     * @param n
     * @return
     */
    public static int fibonacci(int n) {
        if (n == 0) {
            return 0;
        }
        int[] cache = new int[n + 1];
        Arrays.fill(cache, -1);

        cache[0] = 0;
        cache[1] = 1;

        return f(n, cache);
    }

    private static int f(int n, int[] cache) {
        if (cache[n] != -1) {
            return cache[n];
        }

        int x = f(n - 1, cache);
        int y = f(n - 2, cache);
        cache[n] = x + y;   //存入数组
        return cache[n];
    }
}
